package com.ukao.cashregister.ui.arriveShop;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.ReceiveProListAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.ReceiveProClothingBean;
import com.ukao.cashregister.bean.ReceiveProListBean;
import com.ukao.cashregister.bean.ReceiveStoreBean;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.dialog.CrippledDialogFragment;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.pesenter.ArriveShopPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.SystemUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.ArriveShopHomeView;
import com.ukao.cashregister.view.ArriveShopView;
import com.ukao.cashregister.widget.ClearEditText;
import com.ukao.cashregister.widget.DividerDecoration;
import com.ukao.cashregister.widget.ZProgressHUD;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.all_confirmed_btn;

public class ArriveShopFragment extends MvpFragment<ArriveShopPesenter> implements ArriveShopView {


    @BindView(R.id.arrive_shop_from_recycler)
    RecyclerView mFromRecycler;
    @BindView(R.id.arrive_shop_to_recycler)
    RecyclerView mToRecycler;
    Unbinder unbinder;
    ReceiveProListAdapter mFromAdapter;
    ReceiveProListAdapter mToAdapter;

    @BindView(R.id.search_batchCode)
    ClearEditText searchBatchCode;
    @BindView(R.id.fragment_arrive_shop_search1_btn)
    Button fragmentArriveShopSearch1Btn;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.fragment_arrive_shop_search2_btn)
    Button fragmentArriveShopSearch2Btn;
    @BindView(R.id.search_clothcode)
    ClearEditText searchClothcode;
    @BindView(R.id.code)
    TextView code;
    @BindView(R.id.storeName)
    TextView storeName;
    @BindView(R.id.factoryName)
    TextView factoryName;
    @BindView(R.id.factoryWorkTime)
    TextView factoryWorkTime;

    @BindView(R.id.arrive_shop_clothing_from)
    TextView arriveShopClothingFrom;
    @BindView(R.id.arrive_shop_clothing_to)
    TextView arriveShopClothingTo;
    @BindView(R.id.arrive_shop_operator)
    TextView arriveShopOperator;
    @BindView(all_confirmed_btn)
    Button allConfirmedBtn;
    @BindView(R.id.all_confirmed_layout)
    LinearLayout allConfirmedLayout;
    @BindView(R.id.code_describe)
    TextView codeDescribe;
    @BindView(R.id.arrive_to_factory)
    ImageView arriveToFactory;
    @BindView(R.id.leave_factory_text)
    TextView leaveFactoryText;
    @BindView(R.id.remark)
    TextView remark;
    @BindView(R.id.remark_btn)
    Button remarkBtn;
    @BindView(R.id.arrive_show_b1)
    Button arriveShowB1;
    @BindView(R.id.arrive_show_b2)
    Button arriveShowB2;
    @BindView(R.id.arrive_show_b3)
    Button arriveShowB3;
    private ArrayList<ReceiveProListBean> fromLists;
    private ArrayList<ReceiveProListBean> toLists;
    private String outid = "";
    private boolean isOrderEnter;
    private String orderId;
    private ReceiveStoreBean mReceiveStoreBean;
    private ZProgressHUD mProgressDialog;
    private Handler mHandler = new Handler();
    private ArriveShopHomeView arriveShopHomeView;

    public void setArriveShopHomeView(ArriveShopHomeView arriveShopHomeView) {
        this.arriveShopHomeView = arriveShopHomeView;
    }

    public static ArriveShopFragment newInstance(boolean isOrderEnter) {
        ArriveShopFragment childFragment = new ArriveShopFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(ARG_PARAM1, isOrderEnter);
        childFragment.setArguments(bundle);
        return childFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isOrderEnter = getArguments().getBoolean(ARG_PARAM1);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_arrive_shop, null);
        unbinder = ButterKnife.bind(this, view);
        initView();
        setListener();
        initAdapter();
        updateCount();
        return view;
    }


    @Override
    protected ArriveShopPesenter createPresenter() {
        return new ArriveShopPesenter(this);
    }

    @Override
    protected void initView() {
        searchBatchCode.setHint(isOrderEnter ? "出厂订单号" : "出厂批号");
        allConfirmedLayout.setVisibility(View.GONE);
        if (isOrderEnter) {
            codeDescribe.setText("出厂订单号：");
            arriveToFactory.setVisibility(View.INVISIBLE);
            leaveFactoryText.setText("出厂订单衣物");
        }
        searchBatchCode.requestFocus();
        fromLists = new ArrayList<>();
        toLists = new ArrayList<>();
        if (isOrderEnter) {
            int whiteColor = getResource().getColor(R.color.white);
            int blueColor = getResource().getColor(R.color.blue);
            arriveShowB1.setTextColor(blueColor);
            arriveShowB2.setTextColor(whiteColor);
            arriveShowB1.setBackground(getResource().getDrawable(R.drawable.arriveshow_changer_bg_n));
            arriveShowB2.setBackground(getResource().getDrawable(R.drawable.arriveshow_changer_bg_y));
        }
    }

    private void updateCount() {
        if (fromLists.size() == 0) {
            allConfirmedLayout.setVisibility(View.GONE);
        } else if (allConfirmedLayout.getVisibility() == View.GONE) {
            allConfirmedLayout.setVisibility(View.VISIBLE);
        }
        arriveShopClothingFrom.setText(fromLists.size() + "");
        arriveShopClothingTo.setText(toLists.size() + "");

    }


    private void setListener() {
        searchBatchCode.setOnEditorActionListener(mOnEditorActionListener);
        searchClothcode.setOnEditorActionListener(mOnEditorActionListener);

    }


    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            L.i("event=" + event + "actionId=" + actionId);
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
                scanQRcode(v);
            }

            return false;
        }
    };


    private void scanQRcode(TextView v) {
        if (v == searchBatchCode) {
            searchBarode();
//            hideSoftInput();

        } else if (v == searchClothcode) {
            search2Click();
//            hideSoftInput();
        }
    }


    private void initAdapter() {
        mFromAdapter = new ReceiveProListAdapter(activity, fromLists);
        mFromRecycler.setLayoutManager(new LinearLayoutManager(activity));
        mFromRecycler.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        mFromRecycler.setAdapter(mFromAdapter);
        mFromRecycler.setFocusable(false);
        mToAdapter = new ReceiveProListAdapter(activity, toLists);
        mToAdapter.setShowBackgroundColor(true);
        mToRecycler.setLayoutManager(new LinearLayoutManager(activity));
        mToRecycler.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        mToRecycler.setAdapter(mToAdapter);
        mToRecycler.setFocusable(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
        unbinder.unbind();
    }


    @OnClick({R.id.fragment_arrive_shop_search1_btn, R.id.fragment_arrive_shop_search2_btn, all_confirmed_btn, R.id.remark_btn, R.id.arrive_show_b1, R.id.arrive_show_b2, R.id.arrive_show_b3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.remark_btn:
                if (CheckUtils.isNull(mReceiveStoreBean)) return;
                CrippledDialogFragment mRemarkDialog = new CrippledDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putBoolean(ARG_PARAM1, true);
                mBundle.putString(ARG_PARAM2, mReceiveStoreBean.getRemark());
                mRemarkDialog.setArguments(mBundle);
                mRemarkDialog.setOnSureClickListener(mDialogListener);
                mRemarkDialog.show(getChildFragmentManager(), CrippledDialogFragment.class.getName());
                break;
            case R.id.fragment_arrive_shop_search1_btn:
                searchBarode();
                break;

            case R.id.fragment_arrive_shop_search2_btn:
                search2Click();
                break;
            case all_confirmed_btn:
                allConfirmedBtn.setEnabled(false);
                showProgressDialogs();
                mvpPresenter.confirmAllStore(_mActivity, isOrderEnter ? orderId : outid, isOrderEnter);
                break;
            case R.id.arrive_show_b1:
                if (isOrderEnter) {
                    arriveShopHomeView.showPositionFragment(0, 1);
                    SaveParamets.saveArriveShopPosition(0);
                }
                break;
            case R.id.arrive_show_b2:
                if (!isOrderEnter) {
                    arriveShopHomeView.showPositionFragment(1, 0);
                    SaveParamets.saveArriveShopPosition(1);
                }
                break;
            case R.id.arrive_show_b3:
                if (isOrderEnter)
                    arriveShopHomeView.showPositionFragment(2, 1);
                else
                    arriveShopHomeView.showPositionFragment(2, 0);
                SaveParamets.saveArriveShopPosition(2);
                break;

        }
    }

    public void showProgressDialogs() {
        if (mProgressDialog == null) {
            mProgressDialog = new ZProgressHUD(_mActivity);
            mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            allConfirmedBtn.setEnabled(true);
                        }
                    }, 1000);

                }
            });
        }
        mProgressDialog.show();


    }

    private OnDialogSureClickListener mDialogListener = new OnDialogSureClickListener() {


        @Override
        public void onSureItemClick(Object message) {
            String mstrRemark = (String) message;
            mvpPresenter.addRemark(_mActivity, orderId, mstrRemark);


        }
    };

    private void searchBarode() {
        String batchCode = getText(searchBatchCode);
        if (batchCode.isEmpty()) return;
        hideSoftInput();
        searchBatchCode.setText("");
        mvpPresenter.receiveStore(_mActivity, batchCode, isOrderEnter);
    }

    private void search2Click() {
        String strClothcode = getText(searchClothcode);
        if (CheckUtils.isEmpty(strClothcode)) return;
        hideSoftInput();
        searchClothcode.setText("");
        for (ReceiveProListBean from : fromLists) {
            if (strClothcode.equals(from.getScanCode())) {
                mvpPresenter.confirmStore(_mActivity, from, isOrderEnter);
                break;
            }
        }
        SearchrequestFocus();
    }


    /**
     * 搜索左边
     *
     * @param model
     */
    @Override
    public void loadReceiveSucceed(ReceiveStoreBean model) {
        mReceiveStoreBean = model;
        if (isOrderEnter) {
            remark.setText(getString(R.string.management_note) + model.getRemark());
            remarkBtn.setVisibility(View.VISIBLE);
        }
        if (isOrderEnter) {/*订单进入*/
            String orderNo = model.getOrderNo();
            orderId = model.getOrderId();
            factoryWorkTime.setText(MyDateUtils.formatDataTime(model.getCreateTime()));
            mvpPresenter.receiveProList(_mActivity, orderId, isOrderEnter);
            code.setText(orderNo);
        } else {
            outid = model.getId() + "";
            mvpPresenter.receiveProList(_mActivity, outid, isOrderEnter);
            code.setText(model.getCode());
            storeName.setText(CheckUtils.isEmptyString(model.getStoreName()));
            factoryName.setText(CheckUtils.isEmptyString(model.getFactoryName()));
            factoryWorkTime.setText(MyDateUtils.formatDataTime(model.getFactoryWorkTime()));
        }
        arriveShopOperator.setText(SaveParamets.getSaveUseName(_mActivity));/*操作人*/


    }

    @Override
    public void loadReceiveProListSucceed(List<ReceiveProListBean> model) {
        fromLists.clear();
        toLists.clear();
        searchBatchCode.setText("");
        for (ReceiveProListBean receiveProListBean : model) {

            if (isOrderEnter) {
                int isStoreStatus = receiveProListBean.getIsStoreStatus();
                if (isStoreStatus == 1) {/*已到店*/
                    toLists.add(receiveProListBean);
                } else {
                    fromLists.add(receiveProListBean);
                }

            } else {
                int isStoreStatus = receiveProListBean.getStoreStatus();
                if (isStoreStatus != 1) {/*未到店*/
                    fromLists.add(receiveProListBean);
                } else {
                    toLists.add(receiveProListBean);
                }

            }
        }
        SearchrequestFocus();
        updateCount();
        mToAdapter.notifyDataSetChanged();
        mFromAdapter.setDatas(fromLists);
    }

    private void SearchrequestFocus() {
        if (CheckUtils.isEmpty(fromLists)) {
//            searchBatchCode.setText("");
            searchBatchCode.requestFocus();
        } else {
//            searchClothcode.setText("");
            searchClothcode.requestFocus();
        }
//        SystemUtils.hideInputmethod(searchBatchCode);
//        SystemUtils.hideInputmethod(searchClothcode);
    }

    @Override
    public void loadConfirmStoreSucceed(String message, ReceiveProListBean from) {
        toLists.add(0, from);
        fromLists.remove(from);
        mFromAdapter.notifyDataSetChanged();
        mToAdapter.notifyDataSetChanged();
        SearchrequestFocus();
        updateCount();
    }

    @Override
    public void loadAddRemark(String msg, String addRemark) {
        T.show(msg);
        mReceiveStoreBean.setRemark(addRemark);
        remark.setText(getString(R.string.management_note) + addRemark);
    }

    @Override
    public void loadFail(String message) {
        T.show(message);
        searchBatchCode.setText("");
        searchClothcode.setText("");
        SearchrequestFocus();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        SearchrequestFocus();
    }

    @Override
    public void loadAallStore(String message) {
        mToAdapter.getDatas().addAll(mFromAdapter.getDatas());
        mToAdapter.notifyDataSetChanged();
        mFromAdapter.getDatas().clear();
        mFromAdapter.notifyDataSetChanged();
        updateCount();


    }

    @Override
    public void allStoreFinish() {
        if (!allConfirmedBtn.isEnabled()) allConfirmedBtn.setEnabled(true);
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void loadClothingArriveSuccessd(ReceiveProClothingBean model) {

    }
}
